package com.flycms.modules.score.service.impl;

import com.flycms.common.utils.DateUtils;
import com.flycms.common.utils.SnowFlakeUtils;
import com.flycms.common.utils.StrUtils;
import com.flycms.common.utils.bean.BeanConvertor;
import com.flycms.common.utils.page.Pager;
import com.flycms.modules.score.domain.ScoreDetail;
import com.flycms.modules.score.domain.ScoreRule;
import com.flycms.modules.score.domain.dto.ScoreRuleDTO;
import com.flycms.modules.score.mapper.ScoreRuleMapper;
import com.flycms.modules.score.service.IScoreDetailService;
import com.flycms.modules.score.service.IScoreRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 
 * 开发公司：97560.com<br/>
 * 版权：97560.com<br/>
 * <p>
 * 
 * 积分模块---积分规则服务类
 * 
 * <p>
 * 
 * 区分　责任人　日期　　　　说明<br/>
 * 创建　孙开飞　2017年10月15日 　<br/>
 * <p>
 * *******
 * <p>
 * 
 * @author sun-kaifei
 * @email admin@97560.com
 * @version 1.0<br/>
 * 
 */
@Service
public class ScoreRuleServiceImpl implements IScoreRuleService {
    @Autowired
    private ScoreRuleMapper scoreRuleMapper;

    @Autowired
    private IScoreDetailService scoreDetailService;


    // ///////////////////////////////
    // /////     增加         ////////
    // ///////////////////////////////
    /**
     * 新增积分规则
     *
     * @param scoreRule 积分规则
     * @return 结果
     */
    @Override
    public int insertScoreRule(ScoreRule scoreRule)
    {
        scoreRule.setId(SnowFlakeUtils.nextId());
        scoreRule.setCreateTime(DateUtils.getNowDate());
        return scoreRuleMapper.insertScoreRule(scoreRule);
    }

    /////////////////////////////////
    ///////        刪除      ////////
    /////////////////////////////////

    /**
     * 批量删除积分规则
     *
     * @param ids 需要删除的积分规则ID
     * @return 结果
     */
    @Override
    public int deleteScoreRuleByIds(Long[] ids)
    {
        return scoreRuleMapper.deleteScoreRuleByIds(ids);
    }

    /**
     * 删除积分规则信息
     *
     * @param id 积分规则ID
     * @return 结果
     */
    @Override
    public int deleteScoreRuleById(Long id)
    {
        return scoreRuleMapper.deleteScoreRuleById(id);
    }


    // ///////////////////////////////
    // /////        修改      ////////
    // ///////////////////////////////
    /**
     * 修改积分规则
     *
     * @param scoreRule 积分规则
     * @return 结果
     */
    @Override
    public int updateScoreRule(ScoreRule scoreRule)
    {
        scoreRule.setUpdateTime(DateUtils.getNowDate());
        return scoreRuleMapper.updateScoreRule(scoreRule);
    }

    /**
     * 按id查询规则
     *
     * @param status 规则状态
     * @param id 规则ID
     * @return
     */
    @Override
    public int updateScoreRuleEnabled(String status, Long id) {
        return scoreRuleMapper.updateScoreRuleEnabled(status,id);
    }

    // ///////////////////////////////
    // /////        查詢      ////////
    // ///////////////////////////////
    /**
     * 根据规则名称查找
     *
     * @param name 规则名称
     * @return
     */
    @Override
    public ScoreRule findScoreRuleByName(String name) {
        return scoreRuleMapper.findScoreRuleByName(name);
    }

    /**
     * 根据规则id查找和审核状态查询
     * 
     * @param id
     * @return
     */
    @Override
    public ScoreRule findScoreRuleById(Long id) {
        return scoreRuleMapper.findScoreRuleById(id);
    }

    /**
     * 根据积分规则奖励
     * @param userId
     * @param scoreRuleId
     */
    public void scoreRuleBonus(Long userId, Long scoreRuleId) {
        this.scoreRuleBonus(userId,scoreRuleId,null);
    }

    /**
     * 根据积分规则奖励
     * @param userId
     *        用户id
     * @param scoreRuleId
     *        积分规则id
     * @param foreignId
     *        奖励的信息编号id
     */
    public void scoreRuleBonus(Long userId, Long scoreRuleId, Long foreignId) {
        //规则开启状态下才执行奖励
    	ScoreRule scoreRule = this.findScoreRuleById(scoreRuleId);
        if(scoreRule != null){
        	if(scoreRule.getScore() != 0){
                String type = scoreRule.getType();
                boolean canBonus = true;
                ScoreDetail scoreDetail = new ScoreDetail();
                scoreDetail.setType(type);
                scoreDetail.setUserId(userId);
                scoreDetail.setForeignId(foreignId);;
                scoreDetail.setScore(scoreRule.getScore());
                scoreDetail.setRemark(scoreRule.getName());
                scoreDetail.setScoreRuleId(scoreRuleId);
                //unlimite为不限制奖励次数
                if(!"unlimite".equals(type)){
                	canBonus = scoreDetailService.scoreDetailCanBonus(userId, scoreRuleId, type);
                    if(canBonus){
                        //每个会员、每个奖励规则、每个外键（不包含0）只能奖励一次
                        if(scoreDetailService.findByForeignAndRule(userId, scoreRuleId, foreignId) == null){
                            scoreDetailService.saveScoreDetail(scoreDetail,"plus");
                        }
                    }
                }else{
                    scoreDetailService.saveScoreDetail(scoreDetail,"plus");
                }

            }
        }
    }

    public void scoreRuleCancelBonus(Long userId, Long scoreRuleId, Long foreignId) {
        ScoreDetail scoreDetail = scoreDetailService.findByForeignAndRule(userId, scoreRuleId, foreignId);
        if(scoreDetail != null){
            scoreDetailService.scoreDetailByCancel(scoreDetail.getId());
            //扣除积分
           // userDao.updateScore("reduce",scoreDetail.getScore(), userId);
            scoreDetail.setType(scoreDetail.getType());
            scoreDetail.setUserId(userId);
            scoreDetail.setForeignId(foreignId);;
            scoreDetail.setScore(-scoreDetail.getScore());
            scoreDetail.setRemark("撤销积分奖励");
            scoreDetail.setScoreRuleId(scoreRuleId);
            scoreDetailService.saveScoreDetail(scoreDetail,"reduce");
        }
    }

    /**
     * 查询积分规则列表
     *
     * @param scoreRule 积分规则
     * @return 积分规则
     */
    @Override
    public Pager<ScoreRuleDTO> selectScoreRulePager(ScoreRule scoreRule, Integer page, Integer pageSize, String sort, String order)
    {
        Pager<ScoreRuleDTO> pager=new Pager(page,pageSize);
        //排序设置
        if (!StrUtils.isEmpty(sort)) {
            Boolean rank = "desc".equals(order) ? true : false;
            pager.addOrderProperty(sort, rank,true);
        }
        //使用limit进行查询翻页
        pager.addLimitProperty(true);
        pager.setEntity(scoreRule);

        List<ScoreRule> scoreRuleList=scoreRuleMapper.selectScoreRulePager(pager);
        List<ScoreRuleDTO> dtolsit = new ArrayList<ScoreRuleDTO>();
        scoreRuleList.forEach(entity -> {
            ScoreRuleDTO dto = new ScoreRuleDTO();
            dto.setId(entity.getId());
            dto.setName(entity.getName());
            dto.setRemark(entity.getRemark());
            dto.setScore(entity.getScore());
            dto.setType(entity.getType());
            dto.setStatus(entity.getStatus());
            dto.setCreateTime(entity.getCreateTime());
            dtolsit.add(dto);
        });
        pager.setList(dtolsit);
        pager.setTotal(scoreRuleMapper.queryScoreRuleTotal(pager));
        return pager;
    }

    /**
     * 查询需要导出的积分规则列表
     *
     * @param scoreRule 积分规则
     * @return 积分规则集合
     */
    @Override
    public List<ScoreRuleDTO> exportScoreRuleList(ScoreRule scoreRule) {
        return BeanConvertor.copyList(scoreRuleMapper.exportScoreRuleList(scoreRule),ScoreRuleDTO.class);
    }
}
